/**
 * 
 */
package com.yangtao.prototype.system.dao;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Repository;

import com.yangtao.framework.hibernate.BaseDao;
import com.yangtao.prototype.system.entity.FunctionAuthority;
import com.yangtao.prototype.system.entity.MenuTree;
import com.yangtao.prototype.system.entity.Role;

/**
 * @author 杨涛
 * 
 */
@Repository
public class RoleDAO extends BaseDao<Role> {
	public void addRoleAuth(Role role, String[] menus) {
		saveOrUpdate(role);
		String sql = "delete from FunctionAuthority a where a.role.id='"
				+ role.getId();
		batchExecute(sql);
		for (String menu : menus) {
			FunctionAuthority functionAuthority = new FunctionAuthority();
			functionAuthority.setRole(role);
			functionAuthority.setMenu(getHibernateTemplate().load(
					MenuTree.class, menu));
			save(functionAuthority);
		}

	}

	/**
	 * 根据主键查询(用于将对象持久化)
	 * 
	 * @param id
	 *            主键
	 * @return 持久化对象
	 */
	public Role load(String id) {
		Role role = super.load(id);
		getHibernateTemplate().initialize(role.getAuths());
		getHibernateTemplate().initialize(role.getUsers());
		return role;
	}

	public void delete(Role role) {
		// 删除主表
		super.delete(role);
		// 删除权限
		// String sql = "delete from Authority a where a.role.id='" +
		// role.getId()
		// + "' and a.resourceType='MENU'";
		// batchExecute(sql);
	}

	public Set<String> loadAuthorizedMenu(String roleId) {
		HashSet<String> set = new HashSet<String>();
		if (StringUtils.isNotEmpty(roleId)) {
			String sql = "select mt.id from MenuTree mt,FunctionAuthority fa where fa.menu=mt and fa.role.id=?";
			List<String> checked = find(sql, roleId);
			set.addAll(checked);
		}
		return set;
	}
}
